import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { queryCalendar } from '../../services/tools';

const Calendar: React.FC = () => {
  const [date, setDate] = useState<string>(new Date().toISOString().split('T')[0]);
  const [calendarData, setCalendarData] = useState<any>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  
  const navigate = useNavigate();
  
  useEffect(() => {
    fetchCalendarData();
  }, [date]);
  
  const fetchCalendarData = async () => {
    try {
      setLoading(true);
      setError('');
      
      const response = await queryCalendar(date);
      
      if (response.code === 200) {
        setCalendarData(response.data);
      } else {
        setError(response.message || '获取万年历数据失败');
      }
    } catch (err: any) {
      setError(err.message || '获取万年历数据失败，请稍后再试');
    } finally {
      setLoading(false);
    }
  };
  
  // 模拟数据（如果API未返回数据）
  const mockCalendarData = {
    date: date,
    lunarDate: '癸卯年四月十一',
    solarTerm: '小满',
    zodiac: '兔',
    yearGanZhi: '癸卯',
    monthGanZhi: '乙巳',
    dayGanZhi: '丁未',
    festivals: ['佛诞节'],
    suitable: ['祭祀', '出行', '结婚', '搬家'],
    avoid: ['开工', '动土', '安葬']
  };
  
  const displayData = calendarData || mockCalendarData;
  
  return (
    <div className="min-h-screen bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
      <div className="max-w-3xl mx-auto bg-white rounded-xl shadow-md overflow-hidden">
        <div className="p-6">
          <h2 className="text-2xl font-bold text-gray-900 text-center mb-6">万年历</h2>
          
          {/* 日期选择 */}
          <div className="mb-8">
            <label htmlFor="date" className="block text-sm font-medium text-gray-700 mb-2">
              选择日期
            </label>
            <input
              type="date"
              id="date"
              className="block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
              value={date}
              onChange={(e) => setDate(e.target.value)}
            />
          </div>
          
          {loading ? (
            <div className="flex justify-center py-8">
              <div className="animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-indigo-500"></div>
            </div>
          ) : error ? (
            <div className="text-red-500 text-center py-8">
              {error}
            </div>
          ) : (
            <div>
              {/* 日期信息 */}
              <div className="bg-indigo-50 p-4 rounded-lg mb-6 text-center">
                <h3 className="text-xl font-medium text-indigo-900">{displayData.date}</h3>
                <p className="text-lg text-indigo-700 mt-1">{displayData.lunarDate}</p>
                {displayData.solarTerm && (
                  <div className="inline-block bg-indigo-100 text-indigo-800 px-2 py-1 rounded mt-2 text-sm">
                    {displayData.solarTerm}
                  </div>
                )}
              </div>
              
              {/* 详细信息 */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
                <div className="border border-gray-200 rounded-lg p-4">
                  <h4 className="text-lg font-medium text-gray-900 mb-2">干支信息</h4>
                  <div className="space-y-2">
                    <div className="flex justify-between">
                      <span className="text-gray-500">年柱：</span>
                      <span className="font-medium">{displayData.yearGanZhi}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-gray-500">月柱：</span>
                      <span className="font-medium">{displayData.monthGanZhi}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-gray-500">日柱：</span>
                      <span className="font-medium">{displayData.dayGanZhi}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-gray-500">生肖：</span>
                      <span className="font-medium">{displayData.zodiac}</span>
                    </div>
                  </div>
                </div>
                
                <div className="border border-gray-200 rounded-lg p-4">
                  <h4 className="text-lg font-medium text-gray-900 mb-2">节日信息</h4>
                  {displayData.festivals && displayData.festivals.length > 0 ? (
                    <div className="flex flex-wrap gap-2">
                      {displayData.festivals.map((festival: string, index: number) => (
                        <span key={index} className="bg-red-100 text-red-800 px-2 py-1 rounded text-sm">
                          {festival}
                        </span>
                      ))}
                    </div>
                  ) : (
                    <p className="text-gray-500">今日无节日</p>
                  )}
                </div>
              </div>
              
              {/* 宜忌信息 */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div className="border border-gray-200 rounded-lg p-4">
                  <h4 className="text-lg font-medium text-green-600 mb-2">宜</h4>
                  {displayData.suitable && displayData.suitable.length > 0 ? (
                    <div className="flex flex-wrap gap-2">
                      {displayData.suitable.map((item: string, index: number) => (
                        <span key={index} className="bg-green-100 text-green-800 px-2 py-1 rounded text-sm">
                          {item}
                        </span>
                      ))}
                    </div>
                  ) : (
                    <p className="text-gray-500">无</p>
                  )}
                </div>
                
                <div className="border border-gray-200 rounded-lg p-4">
                  <h4 className="text-lg font-medium text-red-600 mb-2">忌</h4>
                  {displayData.avoid && displayData.avoid.length > 0 ? (
                    <div className="flex flex-wrap gap-2">
                      {displayData.avoid.map((item: string, index: number) => (
                        <span key={index} className="bg-red-100 text-red-800 px-2 py-1 rounded text-sm">
                          {item}
                        </span>
                      ))}
                    </div>
                  ) : (
                    <p className="text-gray-500">无</p>
                  )}
                </div>
              </div>
            </div>
          )}
          
          {/* 操作按钮 */}
          <div className="mt-8 flex justify-center">
            <button
              onClick={() => navigate('/tools')}
              className="inline-flex items-center px-4 py-2 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
            >
              返回工具列表
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Calendar;
